<template>
  <el-dialog title="积分申报" v-model="openApplyDialog" width="1000px" append-to-body>
    <el-form :model="queryOrgParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="109px">
        <div class="search-container">
            <div>
                <el-form-item label="积分规则" prop="name" style="width: 100%;position: relative;top: 10px;">
                    <el-input
                    v-model="queryOrgParams.name"
                    placeholder="请输入积分规则"
                    clearable
                    @keyup.enter="handleQuery"
                    />
                </el-form-item>
            </div>
            <div class="search-btn-container">
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                <el-button type="danger" icon="Search" @click="handleQuery">查询</el-button>
            </div>
        </div>
        <div style="margin: 10px;float: right;">总积分：{{ scoreSumVal }}分</div>
    </el-form>
    
    <el-table
        v-loading="loading"
        :data="orgScoreList"
        row-key="id"
        :default-expand-all="isExpandAll"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
      <el-table-column label="积分规则" align="left" prop="name" min-width="390px"/>
      <el-table-column label="申报周期" align="left" prop="cycle" width="130px">
        <template #default="scope">
            <!-- 0：月度；1：季度；2：半年 3：年度 -->
            <div v-if="scope.row.cycle==0">月度
              <el-select v-model="scope.row.cycleValue" placeholder="请选择" clearable style="width: 90%;">
                  <el-option
                    v-for="dict in monthOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"/>
              </el-select>
            </div>
            <div v-else-if="scope.row.cycle==1">季度
              <el-select v-model="scope.row.cycleValue" placeholder="请选择" clearable style="width: 90%;">
                  <el-option
                    v-for="dict in jiDuOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"/>
              </el-select>
            </div>
            <div v-else-if="scope.row.cycle==2">半年
              <el-select v-model="scope.row.cycleValue" placeholder="请选择" clearable style="width: 90%;">
                  <el-option
                    v-for="dict in halfYearOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"/>
              </el-select>
            </div>
            <div v-else-if="scope.row.cycle==3">年度
              <el-input v-model="scope.row.cycleValue" style="width: 90%;" :value="curYear" disabled></el-input>
            </div>
            <div v-else></div>
        </template>
      </el-table-column>
      <el-table-column label="分制" align="left" prop="bouns" width="90px">
        <template #default="scope">
          <div v-if="scope.row.level==1">
            <el-tag v-if="scope.row.bouns==1">加分</el-tag>
            <el-tag v-else>减分</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="积分上限" align="left" prop="scoreDayUp" width="90px"></el-table-column>
      <el-table-column label="申报分数" align="left" prop="addScore" min-width="119px">
        <template #default="scope">
          <div v-if="scope.row.level==1">
            <el-input-number v-model="scope.row.addScore" style="width: 100%;" v-if="scope.row.bouns==1" :min="0" :max="getScoreMaxVal(scope.row.scoreDayUp)"></el-input-number>
            <el-input-number v-model="scope.row.addScore" style="width: 100%;" v-else :max="0"></el-input-number>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="原因" align="left" prop="remark" width="99px">
        <template #default="scope">
          <div v-if="scope.row.level==1">
            <a href="#" style="color: red;" @click="goRemark(scope.row)" v-if="scope.row.remark==null || scope.row.remark==''">填写原因</a>
            <a href="#" style="color: red;" @click="viewRemark(scope.row)" v-else>查看原因</a>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitOrgForm">确 定</el-button>
        <el-button @click="cancelOrg">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  <add-remark ref="addRemarkRef" @callBack="callBackRemark"/>
</template>

<script setup>
import { orgItemStat, memberItemStat, applyForAdding } from "@/api/partybuilding/WorkScore";
import AddRemark from './AddRemark.vue'
const openApplyDialog = ref(false);
const { proxy } = getCurrentInstance();
const loading = ref(true);
const showSearch = ref(true);
const orgScoreList = ref([]);
const isExpandAll = ref(false);
const monthOptions = ref([]);
const jiDuOptions = ref([]);
const halfYearOptions = ref([]);
const curYear = ref(null);
curYear.value = new Date().getFullYear();
const typeVal = ref(null);
const addRemarkRef = ref(null);
const mainKeyId = ref(null);
const scoreSumVal = ref(null);

function getMonthOptions() {
  monthOptions.value = [];
  for (let i = 1; i <= 12; i++) {
    monthOptions.value.push({ value: i, label: i + "月" });
  }

  jiDuOptions.value = [];
  jiDuOptions.value.push({ value: 1, label: "第一季度" });
  jiDuOptions.value.push({ value: 2, label: "第二季度" });
  jiDuOptions.value.push({ value: 3, label: "第三季度" });
  jiDuOptions.value.push({ value: 4, label: "第四季度" });

  halfYearOptions.value = [];
  halfYearOptions.value.push({ value: 1, label: "上半年" });
  halfYearOptions.value.push({ value: 2, label:  "下半年" });
}

const data = reactive({
  form: {},
  queryOrgParams: {
    pageNum: 1,
    pageSize: 9000,
    deptId: null,
    deptName: null,
    year: null,
    userId: null,
    nickName: null
  },
  rules: {}
});

const { queryOrgParams, form, rules } = toRefs(data);

const refresh = (deptId, year, type, scoreSum, deptName, userId, nickName) => {
  queryOrgParams.value.deptId = deptId;
  queryOrgParams.value.deptName = deptName;
  queryOrgParams.value.year = year;
  typeVal.value = type;
  scoreSumVal.value = scoreSum;
  if (typeVal.value == 0) {//0个人积分，1组织积分
    queryOrgParams.value.userId = userId;
    queryOrgParams.value.nickName = nickName;
  } else {
    queryOrgParams.value.userId = undefined;
    queryOrgParams.value.nickName = undefined;
  }
  getScoreList();
};

defineExpose({
    refresh
});

function callBackRemark(data) {
  updateTreeNode(mainKeyId.value, data)
}

// 修改树节点的函数
function updateTreeNode(nodeId, newLabel) {
  const findNode = (nodes, id) => {
    for (let i = 0; i < nodes.length; i++) {
      if (nodes[i].id === id) {
        return nodes[i];
      }
      if (nodes[i].children) {
        const found = findNode(nodes[i].children, id);
        if (found) return found;
      }
    }
    return null;
  };

  const node = findNode(orgScoreList.value, nodeId);
  if (node) {
    node.remark = newLabel; // 修改节点标签
  }
}

function goRemark(row) {
  mainKeyId.value = row.id;
  addRemarkRef.value.addRemarkDialog(row.remark, 'add');
}

function viewRemark(row) {
  addRemarkRef.value.addRemarkDialog(row.remark, 'view');
}

// 查询积分
function getScoreList() {
  if (typeVal.value == 0) {//0个人积分，1组织积分
    getMemberScoreList();
  } else {
    getOrgScoreList();
  }
}

/** 查询党员积分列表 */
function getMemberScoreList() {
  loading.value = true;
  memberItemStat(queryOrgParams.value).then(response => {
    orgScoreList.value = proxy.handleTree(response.data);
    openApplyDialog.value = true;
    loading.value = false;
  });
}

/** 查询组织积分列表 */
function getOrgScoreList() {
  loading.value = true;
  orgItemStat(queryOrgParams.value).then(response => {
    orgScoreList.value = proxy.handleTree(response.data);
    openApplyDialog.value = true;
    loading.value = false;
  });
}

function getScoreMaxVal(scoreDayUp) {
  if (scoreDayUp == null || scoreDayUp == "") {
    return 10000;
  }
  return scoreDayUp;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptName: null,
    deptId: null,
    honor: null,
    reward: null,
    teamHonor: null,
    typeOrg: null,
    grantTime: null,
    content: null,
    pictureUrl: null,
    fileUrl: null,
    typePerson: null,
    userId: null,
    userName: null,
    status: null
  };
  userNameList.value = [];
  userIdList.value = [];
  proxy.resetForm("HonorRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryOrgParams.value.pageNum = 1;
  getScoreList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 提交按钮 */
function submitOrgForm() {
  let dataArr = [];
  let isShort = false;
  orgScoreList.value.forEach(item => {
    let subNodeArray = item.children;
    if (subNodeArray != null && subNodeArray.length > 0) {
      subNodeArray.forEach(subNode => {
        if (subNode.cycle==3) {
          subNode.cycleValue = curYear.value;
        }
        if (subNode.addScore!= null && subNode.addScore != "") {
          if (subNode.cycleValue==null || subNode.cycleValue=="") {
            isShort = true;
            return;
          }
          subNode.titleId = subNode.id;
          subNode.title = subNode.name;
          subNode.typeId = item.id;
          subNode.typeName = item.name;
          subNode.yearSign = queryOrgParams.value.year;
          subNode.deptId = queryOrgParams.value.deptId;
          subNode.orgName = queryOrgParams.value.deptName;
          subNode.userId = queryOrgParams.value.userId;
          subNode.userName = queryOrgParams.value.nickName;
          dataArr.push(subNode);
        }
      });
    }
  });
  if (isShort) {
    proxy.$message.error("请选择申报周期");
    return;
  }
  if (dataArr.length == 0) {
    proxy.$message.error("请填写申报分数");
    return;
  }
  applyForAdding(dataArr).then(response => {
    proxy.$modal.msgSuccess("提交成功");
    orgScoreList.value = [];
    openApplyDialog.value = false;
  });
}

// 取消按钮
function cancelOrg() {
  orgScoreList.value = [];
  openApplyDialog.value = false;
  reset();
}

getMonthOptions();
</script>
  
<style lang="scss" scoped>
    .search-container {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .search-btn-container {
            display: flex;
            align-items: center;
         }
    }
</style>
